﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using WindowsGame.Builder;
using WindowsGame.Data;
using WindowsGame.Enums;
using WindowsGame.GameObjects;
using WindowsGame.Library;

namespace WindowsGame.Manager
{
	/// <summary>
	/// GameObjectManager is responsible for managing all objects in game.
	/// </summary>
	public interface IGameObjectManager
	{
		void LoadData(AllData data);
		void UpdateSpaceship();
		void UpdateWeapon();
		void UpdateData();
		void Update(TimeSpan elapsedTime, TimeSpan time, Direction direction, Boolean thrust, Boolean brake, Boolean shoot);
		void Draw();
	}

	public class GameObjectManager : IGameObjectManager
	{
		private GameObjectBuilder gameObjectBuilder;

		private Spaceship spaceship;
		private Weapon weapon;

		private OffsetData[] offsets;
		private IList<String> spaceshipList;
		private IList<String> weaponList;
		private Int32 spaceshipCount, weaponCount;

		public GameObjectManager(GameObjectBuilder gameObjectBuilder)
		{
			this.gameObjectBuilder = gameObjectBuilder;
		}

		public void LoadData(AllData data)
		{
			this.offsets = data.Offsets;
			this.spaceshipList = data.SpaceshipList;
			this.weaponList = data.WeaponList;

			this.spaceshipCount = -1;
			this.weaponCount = -1;

			UpdateSpaceship();
			UpdateWeapon();
			UpdateData();
		}

		public void UpdateSpaceship()
		{
			spaceshipCount++;
			if (spaceshipCount >= spaceshipList.Count)
			{
				spaceshipCount = 0;
			}
		}
		public void UpdateWeapon()
		{
			weaponCount++;
			if (weaponCount >= weaponList.Count)
			{
				weaponCount = 0;
			}
		}

		public void UpdateData()
		{
			String spaceshipType = spaceshipList[spaceshipCount];
			String weaponType = weaponList[weaponCount];

			spaceship = gameObjectBuilder.BuildGameObject<Spaceship>(spaceshipType);
			weapon = gameObjectBuilder.BuildGameObject<Weapon>(weaponType);

			ShipClass shipClass = spaceship.ShipClass;
			OffsetData shipOffset = offsets[(Int32)shipClass];
			Vector3 bulletOffset = shipOffset.BulletOffset;
			Vector4[] engineOffsets = shipOffset.EngineOffsets;

			spaceship.LoadContent(engineOffsets, Engine.GraphicsManager.PreferredBackBufferWidth, Engine.GraphicsManager.PreferredBackBufferHeight);
			weapon.LoadContent(bulletOffset);
		}

		// Update each game object.
		public void Update(TimeSpan elapsedTime, TimeSpan time, Direction direction, Boolean thrust, Boolean brake, Boolean shoot)
		{
			spaceship.Update(elapsedTime, direction, thrust, brake);
			weapon.Update(time, elapsedTime, shoot, spaceship);
		}

		// Draw each game object.
		public void Draw()
		{
			spaceship.Draw();
			weapon.Draw();
		}

	}
}